#include "stdafx.h"
#include "torrent/DownloadManager.hpp"
#include "torrent/MetaInfo.hpp"

namespace torrent {

	DownloadManager::DownloadManager(DownloadObserver& observer, MetaInfo& metaInfo)
	:_observer(observer), _metaInfo(metaInfo)
	{}
	DownloadManager::~DownloadManager()
	{

	}

	size_t DownloadManager::getBlockIndex(size_t begin)
	{ 
		return static_cast<size_t>(begin / BLOCK_SIZE_IN_PIECE_MSG); 
	}

	size_t DownloadManager::getNumBlocks(size_t pieceIndex) 
	{
		size_t pieceLen = _metaInfo.getPieceLength(pieceIndex);
		return static_cast<size_t>( 
			ceil(pieceLen/ static_cast<double>(BLOCK_SIZE_IN_PIECE_MSG))
			);
	}

	void DownloadManager::addRequestBlockInfo(size_t pieceIdx, size_t begin)
	{
		size_t blockIndex = getBlockIndex(begin);
		DownPieceSet::iterator pos = _downPieceSet.find(pieceIdx);
		if(pos == _downPieceSet.end())
		{
			DownloadingPiece piece(pieceIdx, getNumBlocks(pieceIdx));
			piece._requestedBlocks.set(blockIndex);
			_downPieceSet.insert(piece);
		}
		else
		{
			if(false == pos->_downloadedBlocks.test(blockIndex))
				pos->_requestedBlocks.set(blockIndex);
		}			
	}

	void DownloadManager::addPieceMessage(peer_wire::PiecePtr pieceMsg)
	{
	}
	boost::dynamic_bitset<> DownloadManager::getDownloadedBlockBitfield(size_t pieceIdx)
	{
		boost::dynamic_bitset<> a;
		return a;
	}
	boost::dynamic_bitset<> DownloadManager::getRequestedBlockBitfield(size_t pieceIdx)
	{
		boost::dynamic_bitset<> a;
		return a;
	}
	
	std::vector<size_t> DownloadManager::getAlreadyRequestedPieceIndexes()
	{
		std::vector<size_t> ret;
		ret.push_back(0);
		return ret;
	}
}